package com.tjl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tjl.model.Star;
import com.tjl.model.Uorder;
import com.tjl.service.Impl.UorderServiceImpl;
import com.tjl.util.CodeMsg;
import com.tjl.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author TJL
 * @date 2022/6/1
 * 订单控制器
 */
@RestController
@RequestMapping("/orders")
public class OrderController {
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UorderServiceImpl service;

    @GetMapping
    public CodeMsg getAll(@RequestHeader String token,Integer state){
        Claims claims = null;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }

        QueryWrapper<Uorder> wrapper = new QueryWrapper<>();
        wrapper.eq("uid",claims.getId());
        if (state!=null){
            wrapper.eq("state",state);
        }
        List<Uorder> list = service.list(wrapper);
        //反转集合
        Collections.reverse(list);
        return new CodeMsg(list);
    }

    @PostMapping
    public CodeMsg add(@RequestBody Uorder uorder,@RequestHeader String token){
        Claims claims = null;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        uorder.setUid(Integer.parseInt(claims.getId()));
        return new CodeMsg(service.save(uorder));
    }

    @PutMapping
    public CodeMsg put(@RequestBody Uorder uorder,@RequestHeader String token){
        Claims claims = null;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        uorder.setUid(Integer.parseInt(claims.getId()));
        return new CodeMsg(service.updateById(uorder));
    }

}
